import logging
from rest_framework.response import Response
from rest_framework import status
from voice.models import VoiceProcessingJob
from .command_parser import command_parser
from k8s_ops.services import k8s_service

# 获取logger
logger = logging.getLogger(__name__)

class VoiceCommandProcessor:
    def process_voice_command_internal(self, text, job):
        """内部处理语音指令"""
        try:
            logger.debug(f"开始处理语音文本: {text}")
            
            # 解析指令
            parsed_command = command_parser.parse_command(text)
            logger.debug(f"指令解析结果: {parsed_command}")
            
            # 更新任务状态
            job.parsed_text = str(parsed_command)
            job.status = 'parsing_completed'
            job.save()
            
            if not parsed_command['is_valid']:
                return self._handle_error(job, f"指令解析失败: {parsed_command['error']}", parsed_command)
            
            # 根据指令类型执行相应操作
            action_handlers = {
                'create': self._handle_create_operation,
                'delete': self._handle_delete_operation,
                'get': self._handle_get_operation,
                'update': self._handle_update_operation,
                'describe': self._handle_describe_operation,
                'apply': self._handle_apply_operation,
            }
            
            handler = action_handlers.get(parsed_command['action'])
            if handler:
                return handler(parsed_command, job)
            else:
                return self._handle_error(job, f"暂不支持的操作: {parsed_command['action']}", parsed_command)
                
        except Exception as e:
            logger.error(f"处理指令时发生错误: {str(e)}", exc_info=True)
            return self._handle_error(job, f"处理指令时发生错误: {str(e)}")
    
    def _handle_operation(self, parsed_command, job, operation_type, success_message, error_message_prefix):
        """统一的操作处理函数"""
        resource_type = parsed_command['resource']
        resource_name = parsed_command.get('pinyin_name')
        namespace = parsed_command['details'].get('namespace')
        
        logger.debug(f"{operation_type}操作 - 资源类型: {resource_type}, 拼音名称: {resource_name}")
        
        try:
            # 获取对应的服务方法
            service_methods = {
                'create': {
                    'namespace': (k8s_service.create_namespace, [resource_name]),
                    # 'pv': (k8s_service.create_pv, [resource_name]),
                    # 'pvc': (k8s_service.create_pvc, [resource_name, namespace]),
                    # 'storageclass': (k8s_service.create_storageclass, [resource_name]),
                    # 'ingress': (k8s_service.create_ingress, [resource_name, namespace]),
                },
                'delete': {
                    'namespace': (k8s_service.delete_namespace, [resource_name]),
                    # 'pv': (k8s_service.delete_pv, [resource_name]),
                    # 'pvc': (k8s_service.delete_pvc, [resource_name, namespace]),
                },
                'get': {
                    'namespace': (k8s_service.list_namespaces, []),
                    # 'pv': (k8s_service.list_pvs, []),
                    # 'pvc': (k8s_service.list_pvcs, [namespace]),
                }
            }
            
            # 检查是否支持该资源类型
            if resource_type not in service_methods.get(operation_type, {}):
                return self._handle_error(
                    job, 
                    f"暂不支持{operation_type}{resource_type}资源", 
                    parsed_command,
                    status.HTTP_400_BAD_REQUEST
                )
            
            # 获取服务方法和参数
            service_method, args = service_methods[operation_type][resource_type]
            
            # 调用服务方法
            result = service_method(*args, **parsed_command['details'])
            
            # 更新任务状态
            job.status = 'completed'
            job.result = success_message.format(
                resource_type=resource_type,
                resource_name=resource_name or '',
                namespace=namespace or ''
            )
            job.save()
            
            return Response({
                "success": True,
                "message": success_message.format(
                    resource_type=resource_type,
                    resource_name=resource_name or '',
                    namespace=namespace or ''
                ),
                "parsed_command": parsed_command,
                "api_result": result
            })
            
        except Exception as e:
            error_msg = f"{error_message_prefix}{resource_type}时发生错误: {str(e)}"
            logger.error(error_msg, exc_info=True)
            return self._handle_error(job, error_msg, parsed_command)
    
    def _handle_create_operation(self, parsed_command, job):
        """处理创建操作"""
        return self._handle_operation(
            parsed_command, 
            job, 
            'create',
            "{resource_type} {resource_name} 创建成功",
            "创建"
        )
    
    def _handle_delete_operation(self, parsed_command, job):
        """处理删除操作"""
        return self._handle_operation(
            parsed_command, 
            job, 
            'delete',
            "{resource_type} {resource_name} 删除成功",
            "删除"
        )
    
    def _handle_get_operation(self, parsed_command, job):
        """处理查看操作"""
        return self._handle_operation(
            parsed_command, 
            job, 
            'get',
            "获取{resource_type}列表成功",
            "查看"
        )
    
    def _handle_update_operation(self, parsed_command, job):
        """处理更新操作"""
        return self._handle_error(job, "更新操作暂未实现", parsed_command)
    
    def _handle_describe_operation(self, parsed_command, job):
        """处理描述操作"""
        return self._handle_error(job, "描述操作暂未实现", parsed_command)
    
    def _handle_apply_operation(self, parsed_command, job):
        """处理应用操作"""
        return self._handle_error(job, "应用操作暂未实现", parsed_command)
    
    def _handle_error(self, job, error_message, parsed_command=None, http_status=status.HTTP_400_BAD_REQUEST):
        """统一的错误处理函数"""
        job.status = 'failed'
        job.error_message = error_message
        job.save()
        logger.warning(error_message)
        
        response_data = {"error": error_message}
        if parsed_command:
            response_data["parsed_command"] = parsed_command
            
        return Response(response_data, status=http_status)

# 创建单例实例
voice_command_processor = VoiceCommandProcessor()